package com.tree.experiment.quietcam;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioEncoder;
import android.media.MediaRecorder.VideoEncoder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.text.style.TextAppearanceSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends FragmentActivity implements ActionBar.OnNavigationListener,
SearchView.OnQueryTextListener, View.OnClickListener, SearchView.OnCloseListener, SurfaceHolder.Callback, 
AutoFocusCallback, PreviewCallback  {

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private TextView textView1;
    private SearchView mSearchView;
    private ActionBar mActionBar;
    private WebView webview1;
    private RelativeLayout relative;
    private boolean isClosed;
    private SurfaceView prSurfaceView;
    private ToggleButton prPhotoBtn;
    private ToggleButton prVideoBtn;
    private boolean prRecordInProcess;
    private SurfaceHolder prSurfaceHolder;
    private Camera prCamera;
	private final String cVideoFilePath = Environment.getExternalStorageDirectory().getPath() + "/r10videocam/";
	private MediaRecorder prMediaRecorder;
	private final int cMaxRecordDurationInMs = 30000;
	private final long cMaxFileSizeInBytes = 5000000;
	private final int cFrameRate = 31;
	private File prRecordedFile;
	private final int originalBgColor = 0;
	private boolean isFullScreen = false;
	private boolean isBlackedOut = false;
	private int backBtnCount = 0;
	private OrientationEventListener mOrientationListener;
	

	public static void setCameraDisplayOrientation(Activity activity,
	         int cameraId, android.hardware.Camera camera) {
	     android.hardware.Camera.CameraInfo info =
	             new android.hardware.Camera.CameraInfo();
	     android.hardware.Camera.getCameraInfo(cameraId, info);
	     int rotation = activity.getWindowManager().getDefaultDisplay()
	             .getRotation();
	     int degrees = 0;
	     switch (rotation) {
	         case Surface.ROTATION_0: degrees = 0; break;
	         case Surface.ROTATION_90: degrees = 90; break;
	         case Surface.ROTATION_180: degrees = 180; break;
	         case Surface.ROTATION_270: degrees = 270; break;
	     }

	     int result;
	     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
	         result = (info.orientation + degrees) % 360;
	         result = (360 - result) % 360;  // compensate the mirror
	     } else {  // back-facing
	         result = (info.orientation - degrees + 360) % 360;
	     }
	     if (camera != null)
	    	 camera.setDisplayOrientation(result);
	 }
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                
            	MainActivity.setCameraDisplayOrientation(MainActivity.this,
            			0, prCamera);
            }
        };
        mOrientationListener.enable();
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
        setProgressBarIndeterminateVisibility(Boolean.FALSE);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        
        File lf = new File(cVideoFilePath);
		try {
			if (lf.exists()) {
				//directory already exists
			} else {
				if (lf.mkdirs()) {
					//Log.v(TAG, "createDirIfNotExist created " + _path);
				} else {
					//Log.v(TAG, "createDirIfNotExist failed to create " + _path);
				}
			}
		} catch (Exception e) {
			//create directory failed
			//Log.v(TAG, "createDirIfNotExist failed to create " + _path);
		}
		try
		{
        this.prPhotoBtn = (ToggleButton) this.findViewById(R.id.toggleButton1);
        this.prVideoBtn = (ToggleButton) this.findViewById(R.id.toggleButton2);
        prRecordInProcess = false;
        prSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
        
        
        
        //prSurfaceView = new SurfaceView(this);
//        WindowManager wm = (WindowManager) this.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//        LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
//                    WindowManager.LayoutParams.WRAP_CONTENT,
//                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
//                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
//                    PixelFormat.TRANSLUCENT);        
//        wm.addView(prSurfaceView, params);
        //prSurfaceView.setVisibility(View.INVISIBLE);
       
        prSurfaceHolder = prSurfaceView.getHolder();
           // necessary
       
        //prSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        prSurfaceHolder.addCallback(this);
        prMediaRecorder = new MediaRecorder();
        

        
        this.prPhotoBtn.setOnClickListener(new View.OnClickListener() {
			//@Override
			public void onClick(View v) {
				if (prRecordInProcess == false) {
					startRecording();
				} else {
					stopRecording();
				}
			}
		});
        
        
        webview1 = (WebView) this.findViewById(R.id.webView1);
        SeekBar seekBar1 = (SeekBar) this.findViewById(R.id.seekBar1);
        seekBar1.setProgress(seekBar1.getMax());
        //this.originalBgColor = webview1.getBackground()
        this.prVideoBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isBlackedOut)
				{
					android.view.WindowManager.LayoutParams params = getWindow().getAttributes();
					params.screenBrightness = 0;
					getWindow().setAttributes(params);
					
//
//					try {
//						Process p = Runtime.getRuntime().exec("su");
//						//p.waitFor();
//						Runtime.getRuntime().exec("echo 0 > /system/class/leds/keyboard-backlight/brightness");
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
				}
				if (!isFullScreen)
				{
					getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
					getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
				}
				else
				{
					 
					getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
				}
//				View view = getWindow().getDecorView();
//			    view.setBackgroundColor(Color.TRANSPARENT);
//		        view.setAlpha(0.5f);
//		        webview1.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
		        isFullScreen = !isFullScreen;
		        isBlackedOut = !isBlackedOut;
				//webview1.setBackgroundColor(Color.TRANSPARENT);
				//webview1.setBackgroundColor(0xCC000000);
				//webview1.setBackgroundResource(Color.BLUE);
				//
				//webview1.loadData(webData, "text/html", "UTF-8");
				//webview1.loadDataWithBaseURL(webview1.getOriginalUrl(), webData, "text/html", "UTF-8", null);
			}
		});
        
        seekBar1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				float runningAlpha = (float)(seekBar.getProgress())/(float)(seekBar.getMax());
				webview1.setAlpha(runningAlpha);
				//mActionBar.setsetAlpha((float)(seekBar.getProgress())/(float)(seekBar.getMax()));
				prPhotoBtn.setAlpha(runningAlpha);
				prVideoBtn.setAlpha(runningAlpha);
				if (runningAlpha == 0)
					runningAlpha = 0.1f;
				else
					runningAlpha = runningAlpha * 1.5f;
				seekBar.setAlpha(runningAlpha);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
        	
        });
        // Set up the action bar.
        //webview1.setsetZOrderOnTop(true); 
        mActionBar = getActionBar();
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayShowHomeEnabled(true);
        relative = new RelativeLayout(mActionBar.getThemedContext());
        mSearchView = new SearchView(mActionBar.getThemedContext());
        mSearchView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setGravity(Gravity.LEFT);
        
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setOnCloseListener(this);
        mSearchView.setFocusable(true);
        mSearchView.setFocusableInTouchMode(true);
        //mSearchView.setSubmitButtonEnabled(true);
        textView1 = new TextView(this);
        textView1.setTextSize(1, 18);
       // textView1.set
        textView1.setTextColor(Color.WHITE);
        mSearchView.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
        
        webview1.setWebViewClient(new WebViewClient() {
        	@Override 
        	public boolean shouldOverrideUrlLoading(WebView view, String url) 
        	{ 
        		//setProgressBarIndeterminateVisibility(Boolean.FALSE); 
        		if (getSupportLoaderManager().hasRunningLoaders()) {
             	   setProgressBarIndeterminateVisibility(Boolean.TRUE); 
             	} else {
             	   setProgressBarIndeterminateVisibility(Boolean.FALSE); 
             	}
        		System.out.println("DDD URL: "+url.toString()); 
        		view.loadUrl(url); 
        		mSearchView.setQuery(url, false);
        		textView1.setText(url);
		        mActionBar.setCustomView(textView1);
        		return true; 
        	}
        });
        
		//webview1.setWebViewClient(new WebViewClient());
        WebSettings webSettings = webview1.getSettings();
        //webSettings.setUserAgentString("foo");
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(true);
        webview1.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
            	MainActivity.this.setProgress(progress * 100);
            }
            

        	
        });
        
        webview1.loadUrl("http://www.google.com");

        
        mSearchView.setOnQueryTextListener(new OnQueryTextListener()
        {

			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub

		        query = query.startsWith("http://") ? query : "http://".concat(query);
		        webview1.loadUrl(query);
		        
		        //mSearchView.setPressed(false);
		        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		        imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
		        webview1.requestFocus();
		        textView1.setText(query);
		        mActionBar.setCustomView(textView1);
				return true;
			}
        
        });
        
        relative.addView(mSearchView);
        
        mActionBar.setDisplayShowCustomEnabled(true);
        
        
        textView1.setOnClickListener(new OnClickListener()
        {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mActionBar.setCustomView(relative);
				mSearchView.requestFocus();
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		        imm.showSoftInput(mSearchView, 0);
			}
        	
        });
        textView1.setText("http://www.google.com");
        mActionBar.setCustomView(textView1);
        //actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        //prSurfaceView.setVisibility(View.INVISIBLE);
        
        // Set up the dropdown list navigation in the action bar.
       /* actionBar.setListNavigationCallbacks(
                // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter(
                        actionBar.getThemedContext(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        new String[]{
                                getString(R.string.title_section1),
                                getString(R.string.title_section2),
                                getString(R.string.title_section3),
                        }),
                this);*/
        
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
    }
    
    @Override
    public void onBackPressed() {
    	
    	
    	if (isBlackedOut)
		{	
    		backBtnCount++;
    		if (backBtnCount < 2)
    			return;
    		else
    			backBtnCount = 0;
			android.view.WindowManager.LayoutParams params = getWindow().getAttributes();
			params.screenBrightness = -1;
			getWindow().setAttributes(params);
			Runtime r = Runtime.getRuntime();
			try {
				r.exec("echo 83 > /system/class/leds/keyboard-backlight/brightness");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			isBlackedOut = !isBlackedOut;
			return;
		}
    	
    	
        if (mSearchView.isShown()){
        	mSearchView.onActionViewCollapsed();  //collapse your ActionView

        	if (this.webview1.isFocused() && this.webview1.canGoBack()) {
        		WebBackForwardList wbfl = this.webview1.copyBackForwardList();
        		WebHistoryItem currentHistoryItem = wbfl.getCurrentItem();
        		int currentHistoryIndex = wbfl.getCurrentIndex();
        		int lastHistoryIndex = currentHistoryIndex - 1;
        		WebHistoryItem lastHistoryItem = wbfl.getItemAtIndex(lastHistoryIndex);
        		this.webview1.goBack();  
            	
            	mSearchView.setQuery(lastHistoryItem.getUrl(),false);       //clears your query without submit
            	textView1.setText(lastHistoryItem.getUrl());
		        mActionBar.setCustomView(textView1);
    	    }

            isClosed = true;                     //needed to handle closed by back
        } else if(!this.webview1.canGoBack()){
            super.onBackPressed();
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
    	//if (savedInstanceState.size() > 0)
        //if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
        //    getActionBar().setSelectedNavigationItem(
        //            savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        //}
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
        //        getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.menu_settings:
    	  Intent intent = new  Intent(MainActivity.this,
                  SettingsActivity.class);
    	  startActivity(intent);
    	  break;
      }
      return super.onOptionsItemSelected(item);
    }

    

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given tab is selected, show the tab contents in the container
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
        return true;
    }

    /**
     * A dummy fragment representing a section of the app, but that simply displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        public DummySectionFragment() {
        }

        public static final String ARG_SECTION_NUMBER = "section_number";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            Bundle args = getArguments();
            textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
            return textView;
        }
    }

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		this.relative.setVisibility(View.VISIBLE);
		return false;
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void surfaceChanged(SurfaceHolder _holder, int _format, int _width, int _height) {
		Camera.Parameters lParam = prCamera.getParameters();
//		//lParam.setPreviewSize(_width, _height);
//		//lParam.setPreviewSize(320, 240);
//		lParam.setPreviewFormat(PixelFormat.JPEG);
		System.out.println(prCamera.getParameters().flatten());
		HashMap<String, String> paramsHashMap = CameraParametersUtility.storeCameraParametersToHashMap(lParam);
		//lParam.set("auto-exposure-values", value)
		lParam = CameraParametersUtility.prepareCameraParameters(lParam);
		lParam.setRotation(90);
		
		prCamera.setParameters(lParam);
		try {
			prCamera.setPreviewDisplay(_holder);
			prCamera.setPreviewCallback(this);
			prCamera.startPreview();
			//prPreviewRunning = true;
		} catch (IOException _le) {
			_le.printStackTrace();
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		try
		{
			int camNum = Camera.getNumberOfCameras();
			prCamera = Camera.open(0);
			setCameraDisplayOrientation(this, 0, prCamera);
			if (prCamera == null) {
				Toast.makeText(this.getApplicationContext(), "Camera is not available!", Toast.LENGTH_SHORT).show();
				finish();
			}
		} catch (Exception e)
		{
			e.printStackTrace();

		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		releaseCameraMediaResources();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		releaseCameraMediaResources();
	}

	private void releaseCameraMediaResources()
	{
		if (prRecordInProcess) {
			
			stopRecording();
		} else {
			if (prCamera != null)
			{
				prCamera.setPreviewCallback(null);
				prCamera.stopPreview();
			}
		}
		if (prMediaRecorder != null)
		{
			prMediaRecorder.release();
			prMediaRecorder = null;
		}
		if (prCamera != null)
		{
			prCamera.release();
			prCamera = null;
		}
	}
	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//releaseCameraMediaResources();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//releaseCameraMediaResources();
	}

	private boolean startRecording() {
		prCamera.stopPreview();
		try {
			prCamera.unlock();
			
			
			prMediaRecorder.setCamera(prCamera);
			//set audio source as Microphone, video source as camera
			//state: Initial=>Initialized
			//prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
			prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
			//set the file output format: 3gp or mp4
			//state: Initialized=>DataSourceConfigured
			int videoEncodingFormat = VideoEncoder.H264;
			int containerFormat = MediaRecorder.OutputFormat.MPEG_4;
			int audioEncodingFormat = 0;
			String lVideoFileFullPath;
			String lDisplayMsg = "Current container format: ";
			if (containerFormat == MediaRecorder.OutputFormat.THREE_GPP) {
				lDisplayMsg += "3GP\n";
				lVideoFileFullPath = ".3gp";
				prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			} else if (containerFormat == MediaRecorder.OutputFormat.MPEG_4) {
				lDisplayMsg += "MP4\n";
				lVideoFileFullPath = ".mp4";
				prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			} else {
				lDisplayMsg += "3GP\n";
				lVideoFileFullPath = ".3gp";
				prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			}
			//the encoders: 
			//audio: AMR-NB
			
			prMediaRecorder.setAudioEncoder(AudioEncoder.AAC);
			//video: H.263, MP4-SP, or H.264
			//prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
			//prMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP);
			lDisplayMsg += "Current encoding format: ";
			if (videoEncodingFormat == VideoEncoder.H263) {
				lDisplayMsg += "H263\n";
				prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
			} else if (videoEncodingFormat == VideoEncoder.MPEG_4_SP) {
				lDisplayMsg += "MPEG4-SP\n";
				prMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP);
			} else if (videoEncodingFormat == VideoEncoder.H264) {
				lDisplayMsg += "H264\n";
				prMediaRecorder.setVideoEncoder(VideoEncoder.H264);
			} else {
				lDisplayMsg += "H263\n";
				prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
			}
			
			lVideoFileFullPath = cVideoFilePath + String.valueOf(System.currentTimeMillis()) + lVideoFileFullPath;
			int videoRes = 0;
			prRecordedFile = new File(lVideoFileFullPath);
			prMediaRecorder.setOutputFile(prRecordedFile.getPath());
			/*if (Utils.puResolutionChoice == SettingsDialog.cpuRes176) {
				prMediaRecorder.setVideoSize(176, 144); 
			} else if (Utils.puResolutionChoice == SettingsDialog.cpuRes320) {
				prMediaRecorder.setVideoSize(320, 240);
			} else if (Utils.puResolutionChoice == SettingsDialog.cpuRes720) {
				prMediaRecorder.setVideoSize(720, 480);
			} */
			prMediaRecorder.setVideoSize(1920, 1080);
			Toast.makeText(this.getApplicationContext(), lDisplayMsg, Toast.LENGTH_LONG).show();
			prMediaRecorder.setVideoEncodingBitRate(20000000);
			prMediaRecorder.setVideoFrameRate(cFrameRate);
			//prSurfaceView.setVisibility(View.VISIBLE);
			prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
			//prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
			//prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
			//prepare for capturing
			//state: DataSourceConfigured => prepared
			prMediaRecorder.prepare();
			//start recording
			//state: prepared => recording
			prMediaRecorder.start();
			prCamera.autoFocus(this);
			this.prVideoBtn.setText("Stop");
			prRecordInProcess = true;
			return true;
		} catch (IOException _le) {
			_le.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private void stopRecording() {
		prMediaRecorder.stop();
		prMediaRecorder.reset();
		try {
			prCamera.reconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.prVideoBtn.setText("Start");
		prRecordInProcess = false;
		prCamera.startPreview();
	}

	@Override
	public void onAutoFocus(boolean success, Camera camera) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPreviewFrame(byte[] arg0, Camera arg1) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

	    if(event.getAction() == KeyEvent.ACTION_DOWN)
	    {
	        switch(keyCode)
	        {
	        case KeyEvent.KEYCODE_CAMERA:
	            //videoPreview.TakePicture();
	            return true;
	        }
	    }

	    return super.onKeyDown(keyCode, event);
	}
}
